<?php


namespace app\project\admin;


use app\admin\controller\Admin;
use app\project\model\Category as ModelCategory;
use app\common\builder\ZBuilder;
use app\project\model\Config;
use app\project\model\ProjectUuid;
use app\user\model\User;
use util\Tree;

/**
 * 项目分类表
 * Class Category
 * @package app\project\admin
 */
class Category extends Admin
{
    public function initialize()
    {
        parent::initialize();
        $this->model = new ModelCategory();
    }

    /**
     * 当前权限
     * @return mixed
     * @throws \think\Exception
     */
    public function getCategoryList()
    {
        $data = $this->model->with(['adminUser'])->order('sort','asc')->select();
        $data = Tree::toList($data);
//        dump($data_list);die;
        $btn_del = [
            'title' => '删除',
            'icon'  => 'fa fa-times',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href'  => url('del', ['ids' => '__id__']),
            'data-title'=>'真的要删除吗?'
        ];
        $btn_dels =
        [
            'title'       => '删除',
            'icon'        => 'fa fa-times-circle-o',
            'class'       => 'btn btn-danger ajax-post confirm',
            'target-form' => 'ids',
            'href'  => url('del'),
            'data-title'=>'真的要删除吗?'
        ];
        return ZBuilder::make('table')
            ->addColumns([
                ['id', '序号'],
                ['title', '项目名'],
                ['title', '栏目名称', 'callback', function($value, $data){
                    return isset($data['title_prefix']) ? $data['title_display'] : $value;
                }, '__data__'],
                ['icon', '封面', 'picture'],
                ['principal_name', '负责人'],
                ['sort', '排序','text.edit'],
//                ['status', '状态', 'switch'],
                ['create_time', '创建时间', 'datetime'],
                ['update_time', '修改时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add', [],true)//
            ->addTopButton('del',$btn_dels)
            ->addRightButton('edit', [],true)
            ->addRightButton('del',$btn_del)
            ->setRowList($data)
            ->fetch();
    }

    public function add($pid = 0)
    {
        $config = Config::field('title,key,value')->select()->toArray();

        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            $result = $this->validate($data, 'Category');
            if (true !== $result) {
                $this->error($result);
            }
            $json = [];
            foreach ($config as$value){
                if (isset($data[$value['key']])&&$data[$value['key']]!=0){
                    $value['value'] = $data[$value['key']];
                    $json[] = $value;
                }
            }
            $data['setting']['jishu'] = $json;
            $data['setting']['shengyu'] = $json;
            if ($info = $this->model->create($data)) {
                $details = UID . '操作category_add,id为' . $info['id'];
                action_log('category_add', 'project_category', $info['id'], UID, $details);
                $this->success('新增成功','getCategoryList',['_parent_reload'=>1,'_close_pop'=>1]);
            }
            $this->error('新增失败');
        }
        $ids = $this->model->where('pid',0)->column('id');

        $addFormItems =  [
            ['select', 'pid', '所属栏目', '<span class="text-danger">必选</span>', $this->model->getTreeList(), $pid],
            ['select', 'project_uuid', '项目号', '<span class="text-danger">子项目必选</span>', ProjectUuid::column('project_uuid','id')],
            ['text', 'title', '标题'],
            ['image', 'icon', '封面'],
            ['select', 'principal', '项目负责人', '除超级管理员外，拥有该节点权限的角色', User::where('role', '=', 2)->column('id,username'),UID],
            ['select', 'team', '团队负责人', '除超级管理员外，拥有该节点权限的角色', User::where('role', '=', 3)->column('id,username'),UID],
            ['number', 'sort', '排序', '数字越小越靠前', 99, 0, 100],
            ['number', 'money', '项目总资金(万)', '请输入数字,50万直接输入50'],
        ];
        $show = 'principal,team,project_uuid,money';
        foreach ($config as $value){
            $addFormItems[] = ['number',$value['key'],$value['title'], '<span class="text-danger">填入比例,没有则填0,例如20%,填入20!</span>',$value['value']];
            $show.= ','.$value['key'];
        }

        // 使用ZBuilder构建表单页面
        return ZBuilder::make('form')
            ->setPageTips('新增项目分类')
            ->hideBtn(['back'])
            ->addFormItems($addFormItems)
            ->setTrigger('pid',implode(',',$ids), $show)
            ->fetch();
    }

    /**
     * 这里需要判断权限
     * @param int $id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = 0)
    {
        if ($id === 0) {
            $this->error('缺少参数');
        }
        $info = $this->model->get($id);
        if (!$info) {
            $this->error('缺少数据');
        }
        $config = Config::field('title,key,value')->select()->toArray();
        if ($this->request->isPost()) {
            $data = $this->request->param('', null, 'trim');
            $result = $this->validate($data, 'Category');
            if (true !== $result) {
                $this->error($result);
            }
            $json = [];
            foreach ($config as$value){
                if (isset($data[$value['key']])&&$data[$value['key']]!=0){
                    $value['value'] = $data[$value['key']];
                    $json[] = $value;
                }
            }
            $data['setting']['jishu'] = $json;
            $data['setting']['shengyu'] = $info->setting->shengyu;
            $data['update_time'] = time();
            if ($info = $this->model->where('id', $id)->update($data)) {
                $details = UID . '操作category_edit,id为' . $info['id'];
                action_log('category_edit', 'project_category', $info['id'], UID, $details);
                $this->success('编辑成功','getCategoryList',['_parent_reload'=>1,'_close_pop'=>1]);
            }
            $this->error('编辑失败');
        }

        $ids = $this->model->where('pid',0)->column('id');
        $addFormItems = [
            ['select', 'pid', '所属栏目', '<span class="text-danger">必选</span>', $this->model->getTreeList(), $info['pid']],
            ['select', 'project_uuid', '项目号', '<span class="text-danger">子项目必选</span>', ProjectUuid::column('project_uuid','id')],
            ['text', 'title', '标题'],
            ['image', 'icon', '封面'],
            ['select', 'principal', '项目负责人', '除超级管理员外，拥有该节点权限的角色', User::where('role', '=', 2)->column('id,username')],
            ['select', 'team', '团队负责人', '除超级管理员外，拥有该节点权限的角色', User::where('role', '=', 3)->column('id,username')],
            ['number', 'sort', '排序', '数字越小越靠前', 99, 0, 100],
            ['number', 'money', '项目总资金(万)', '请输入数字,50万直接输入50'],
        ];
        $info = json_decode($info,true);
        if(isset($info['setting']['jishu'])){
            foreach ($info['setting']['jishu'] as $value){
                $addFormItems[] = ['number',$value['key'],$value['title'], '<span class="text-danger">填入比例,没有则填0,例如20%,填入20!</span>',$value['value']];
            }
        }
        return ZBuilder::make('form')
            ->setPageTips('编辑项目分类')
            ->hideBtn(['back'])
            ->addFormItems($addFormItems)
            ->setFormData($info)
            ->setTrigger('pid',implode(',',$ids), 'principal,team,project_uuid,money')
            ->submitConfirm()
            ->fetch();
    }

    /**
     * 这里需要判断权限
     * @param int $id
     * @return mixed
     * @throws \think\Exception
     */
    public function del($ids = 0)
    {
        if ($ids == 0){
            $ids = $this->request->post('ids', null, 'trim');
        }
        $this->model->destroy(['id'=>$ids]);
        $this->success('删除成功');
    }


}